import React, { useState, useEffect, useRef } from 'react';
import TaskSummary from './TaskSummary';
import DistributionChart from './DistributionChart';
import TaskTable from './TaskTable';
import AddDataSourceModal from './AddDataSourceModal';
import ERModelConfigModal from './ERModelConfigModal';
import TaskDetailsModal from './TaskDetailsModal';
import API from '../../api/client';

const DataSourceManager = ({ 
  showAddDataSourceModal,   
  closeDataSourceModal,
  refreshDataSources,
  dataSourceTypes,
  erModels = { items: [] },
  refreshErModels
}) => {
  const safeErModels = erModels.items || [];
  const [isAddERModalVisible, setAddERModalVisible] = useState(false);
  const [selectedDataSource, setSelectedDataSource] = useState(null);
  const [tasks, setTasks] = useState([]);
  const [loadingTasks, setLoadingTasks] = useState(true);
  const [runningTasks, setRunningTasks] = useState(new Set());
  const [pollingTimers, setPollingTimers] = useState({});
  const [taskStats, setTaskStats] = useState(null);
  const [dbDistribution, setDbDistribution] = useState([]);
  const [selectedTaskId, setSelectedTaskId] = useState(null);
  const [taskDetails, setTaskDetails] = useState(null);
  const [isDetailsModalVisible, setIsDetailsModalVisible] = useState(false);
  const [loadingDetails, setLoadingDetails] = useState(false);
  
  // 使用 ref 存储任务状态，避免闭包问题
  const tasksRef = useRef([]);
  const runningTasksRef = useRef(new Set());
  
  const fetchTasks = async () => {
    try {
      setLoadingTasks(true);
      const response = await API.getTasks();
      
      const expandedTasks = [];
      
      // 根据响应结构处理不同的任务数据格式
     const tasksData = response.data || 
        (Array.isArray(response) ? response : 
        (response.items || []));
      
      // 处理每个任务 - 添加过滤确保任务对象有效
      tasksData.filter(task => task).forEach(task => {
        // 如果任务有er_models数组
        if (task.er_models && Array.isArray(task.er_models)) {
          // 为每个ER模型创建单独的任务行
          task.er_models.forEach(erModel => {
            // 关键修改：使用erModel的task_id作为任务ID
            const taskId = erModel.task_id || `${task.id}-${erModel.id}`;
            expandedTasks.push({
              ...task, // 保留原始任务属性
              id: taskId, // 使用ER模型的任务ID作为唯一标识
              er_model: erModel, // 添加单独的er_model对象
              // 从最内层的erModel获取状态和任务ID
              status: erModel.status || 'pending',
              task_id: erModel.task_id || taskId, // 确保task_id字段存在
              er_name: erModel.er_name
            });
          });
        } else {
          // 没有ER模型的任务使用自身的任务ID
          expandedTasks.push({
            ...task,
            er_model: null,
            // 使用task.task_id或生成备用ID
            id: task.task_id || task.id,
            status: task.status || 'pending',
            task_id: task.task_id || task.id // 确保task_id字段存在
          });
        }
      });
      
      console.log("处理后的任务列表:", expandedTasks);
      
      setTasks(expandedTasks);
      tasksRef.current = expandedTasks;
    } catch (error) {
      console.error('获取任务数据失败:', error);
      setTasks([]);
    } finally {
      setLoadingTasks(false);
    }
  };

  const getDbTypeName = (typeId) => {
    const type = dataSourceTypes.find(t => t.id === typeId);
    return type ? type.name : '未知类型';
  };

  // 轮询任务状态
  const startPolling = (taskId) => {
    // 清除可能存在的旧定时器
    if (pollingTimers[taskId]) {
      clearInterval(pollingTimers[taskId]);
    }
    
    // 设置新的轮询
    const intervalId = setInterval(async () => {
      try {
        const statusResponse = await API.pollTaskStatus(taskId);
        const status = statusResponse.status;
        
        // 更新任务状态
        setTasks(prevTasks => {
          const updatedTasks = prevTasks.map(task => 
            task && task.task_id === taskId ? { ...task, status } : task
          );
          tasksRef.current = updatedTasks; // 更新 ref
          return updatedTasks;
        });
        
        // 如果任务完成或失败，停止轮询
        if (status === 'completed' || status === 'failed') {
          clearInterval(intervalId);
          
          // 更新轮询定时器状态
          setPollingTimers(prev => {
            const newTimers = { ...prev };
            delete newTimers[taskId];
            return newTimers;
          });
          
          // 从运行任务集合中移除
          setRunningTasks(prev => {
            const newSet = new Set(prev);
            newSet.delete(taskId);
            runningTasksRef.current = newSet; // 更新 ref
            return newSet;
          });
          
          // 刷新任务列表
          fetchTasks();
        }
      } catch (error) {
        console.error('轮询任务状态失败:', error);
        clearInterval(intervalId);
        
        // 更新轮询定时器状态
        setPollingTimers(prev => {
          const newTimers = { ...prev };
          delete newTimers[taskId];
          return newTimers;
        });
        
        // 更新任务状态为失败
        setTasks(prevTasks => {
          const updatedTasks = prevTasks.map(task => 
            task && task.task_id === taskId ? { ...task, status: 'failed' } : task
          );
          tasksRef.current = updatedTasks;
          return updatedTasks;
        });
        
        // 从运行任务集合中移除
        setRunningTasks(prev => {
          const newSet = new Set(prev);
          newSet.delete(taskId);
          runningTasksRef.current = newSet;
          return newSet;
        });
      }
    }, 5000); // 每5秒轮询一次
    
    // 保存定时器ID
    setPollingTimers(prev => ({
      ...prev,
      [taskId]: intervalId
    }));
    
    // 设置超时检查（最长等待10分钟）
    setTimeout(() => {
      if (pollingTimers[taskId]) {
        clearInterval(intervalId);
        
        // 更新轮询定时器状态
        setPollingTimers(prev => {
          const newTimers = { ...prev };
          delete newTimers[taskId];
          return newTimers;
        });
        
        // 更新任务状态为超时
        setTasks(prevTasks => {
          const updatedTasks = prevTasks.map(task => 
            task && task.task_id === taskId ? { ...task, status: 'timeout' } : task
          );
          tasksRef.current = updatedTasks;
          return updatedTasks;
        });
        
        // 从运行任务集合中移除
        setRunningTasks(prev => {
          const newSet = new Set(prev);
          newSet.delete(taskId);
          runningTasksRef.current = newSet;
          return newSet;
        });
        
        // 刷新任务列表
        fetchTasks();
      }
    }, 10 * 60 * 1000); // 10分钟超时
  };

  // 执行探查任务的处理函数 - 使用taskId作为参数
  const handleRunTask = async (taskId) => {
    // 找到对应的任务行
    const task = tasksRef.current.find(t => t && t.task_id === taskId);
    if (!task) return;
    
    // 添加任务到运行中集合
    setRunningTasks(prev => {
      const newSet = new Set(prev);
      newSet.add(taskId);
      runningTasksRef.current = newSet; // 更新 ref
      return newSet;
    });
    
    try {
      // 调用API启动任务 - 直接使用taskId
      const result = await API.startTask(taskId);
      console.log('任务启动成功:', result);
      
      // 开始轮询任务状态 - 使用taskId
      startPolling(taskId);
    } catch (error) {
      console.error('启动任务失败:', error);
      setTasks(prev => {
        const updatedTasks = prev.map(t => 
          t && t.task_id === taskId ? { ...t, status: 'failed' } : t
        );
        tasksRef.current = updatedTasks;
        return updatedTasks;
      });
      
      setRunningTasks(prev => {
        const newSet = new Set(prev);
        newSet.delete(taskId);
        runningTasksRef.current = newSet;
        return newSet;
      });
    }
  };
  
  // 查看任务详情 - 使用taskId作为参数
  const handleViewDetails = (taskId) => {
    // 设置状态
    setSelectedTaskId(taskId);
    setIsDetailsModalVisible(true);
    setLoadingDetails(true);
    
    // 获取详情 - 直接使用taskId
    API.getTaskResults(taskId)
      .then(response => {
        const details = response.data || response;
        setTaskDetails(details);
      })
      .catch(error => {
        console.error('获取详情失败:', error);
        setTaskDetails({ 
          error: error.message || '无法加载任务详情' 
        });
      })
      .finally(() => {
        setLoadingDetails(false);
      });
  };

  // 获取数据库分布数据
  useEffect(() => {
    const fetchDbDistribution = async () => {
      try {
        const data = await API.getDbDistribution();
        setDbDistribution(data);
      } catch (error) {
        console.error('获取数据库分布数据失败:', error);
        setDbDistribution([]);
      }
    };
    
    fetchDbDistribution();
  }, []);

  // 组件卸载时清除所有轮询定时器
  useEffect(() => {
    return () => {
      Object.values(pollingTimers).forEach(timerId => {
        clearInterval(timerId);
      });
    };
  }, []);

  // 获取统计数据
  useEffect(() => {
    const fetchStats = async () => {
      try {
        const [stats, dist] = await Promise.all([
          API.getTaskStats(),
          API.getDbDistribution()
        ]);
        setTaskStats(stats);
        setDbDistribution(dist);
      } catch (error) {
        console.error('获取统计信息失败:', error);
      }
    };
    
    fetchStats();
  }, []);

  // 初始化加载任务
  useEffect(() => {
    fetchTasks();
  }, []);

  // 同步 ref 和 state
  useEffect(() => {
    tasksRef.current = tasks;
  }, [tasks]);
  
  useEffect(() => {
    runningTasksRef.current = runningTasks;
  }, [runningTasks]);

  return (
    <div className="data-source-manager">
      {isDetailsModalVisible && (
      <TaskDetailsModal 
        taskDetails={taskDetails}
        visible={isDetailsModalVisible}
        onClose={() => {
          setIsDetailsModalVisible(false);
          setTaskDetails(null);
        }}
        loading={loadingDetails}
        selectedTaskId={selectedTaskId} 
      />
    )}

      <TaskSummary stats={taskStats} />
      <DistributionChart data={dbDistribution} />
      <TaskTable 
        tasks={tasks} 
        loading={loadingTasks}
        onRunTask={handleRunTask} // 传递函数
        onViewDetails={handleViewDetails} // 传递函数
        runningTasks={runningTasks}
        dataSourceTypes={dataSourceTypes}
        erModels={safeErModels}
        getDbTypeName={getDbTypeName}
      />
      
      <AddDataSourceModal 
        visible={showAddDataSourceModal}
        onClose={closeDataSourceModal}
        refreshDataSources={refreshDataSources}
        dataSourceTypes={dataSourceTypes}
      />
      <ERModelConfigModal
        visible={isAddERModalVisible}
        onClose={() => setAddERModalVisible(false)}
        dataSourceId={selectedDataSource}
        refreshErModels={refreshErModels}
      />
    </div>
  );
};

export default DataSourceManager;